import React, { Component } from 'react'
import Header from 'router/common/Header'
import Footer from 'router/common/Footer'
import 'css/register/emailToken.scss'
import queryString from 'query-string'
import success from 'images/register/success.png'
import PropTypes from 'prop-types'
import history from 'router/history'
import { userVerify, updateContactEmailSuccess } from 'utils/Api'

class EmailToken extends Component {
  constructor() {
    super()
    this.state = {
      count: 3
    }
  }
  componentDidMount() {
    const { location } = this.props
    const parsed = this.parsedLocation(location)
    if (parsed.email) {
      // 修改邮箱
      var fd = new FormData()
      fd.append('verifyWay', 1)
      fd.append('verify', parsed.email)
      updateContactEmailSuccess(fd, parsed.token)
        .then(({msg}) => {
          if (msg === '200') {
            this.timer = setInterval(() => {
              this.setState(prevState => ({
                count: prevState.count - 1
              }))
              !this.state.count && clearInterval(this.timer)
              !this.state.count && this.callback()
            }, 1000)
          }
          
        })
      return

    }
    if (parsed.token) {
      userVerify(parsed).then(({msg, result}) => {
        if (msg === '200') {
          this.timer = setInterval(() => {
            this.setState(prevState => ({
              count: prevState.count - 1
            }))
            !this.state.count && clearInterval(this.timer)
            !this.state.count && this.callback()
          }, 1000)
        }
      })
    } 
  }
  componentWillUnmount() {
    clearInterval(this.timer)
  }
  parsedLocation(location) {
    return queryString.parse(location.search)
  }
  callback() {
    history.push('/')
  }
  render() {
    const { location } = this.props
    const { email } = this.parsedLocation(location)
    return (
      <div className='register-bg'>
        <Header/>
        <div className='center'>
          <div className='register-content'>
            <div className='topBar'></div>
            <h2 className='register-title'>
              {!email ? '注册精禾云平台账号' : '修改邮箱'}
            </h2>
            <div className='register-success-form center'>
              <div>
                <div className='success-tip'>
                  <img src={success} />
                  <span>恭喜你,邮箱验证成功</span>
                </div>
                <div className='success-token'>
                  <button onClick={this.callback}>跳转登录页面</button>
                    自动跳转倒计时{this.state.count}
                </div>
              </div>
            </div>
          </div>
        </div>
        <Footer/>
      </div>
    )
  }
}
EmailToken.propTypes = {
  location: PropTypes.object
}
export default EmailToken